package algoritmoHiru;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Enumeration;

public class Task1 extends Thread{
	static final int portua=5555;
	public void run(){
		try{
		
		DatagramSocket bidaltzeSocketa=new DatagramSocket();
		//recovered arraya byte [] bihurtzeko
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
	    ObjectOutputStream oos = new ObjectOutputStream(bos);
	    oos.writeObject(Hasieraketa.recovered);
	    oos.flush();
	    oos.close();
	    bos.close();
	    byte [] mezua = bos.toByteArray();
	    /***************************************************/
	    System.out.println(mezua.length);
		DatagramPacket paketea=new DatagramPacket (mezua,mezua.length);
		paketea.setPort(portua);
	    
		MakinaBektorea makinak = MakinaBektorea.getInstance();
		String makinaIp;
		while(true){
			if (Hasieraketa.leader.compareTo(InetAddress.getLocalHost().getHostAddress())==0){//ip-arekin konparaketa
				for (Enumeration<String> e=makinak.hash.keys();e.hasMoreElements();){
					makinaIp=e.nextElement();
					if (Hasieraketa.leader.compareTo(makinaIp)!=0){//nere buruei ez bialtzeko
					paketea.setAddress(InetAddress.getByAddress(makinaIp.getBytes()));//byte array bezala pasa behar zaio ip-a
					bidaltzeSocketa.send(paketea);
					System.out.println("mezua bidali da");
					}
				}
			}
			Thread.sleep(Hasieraketa.zenbakiKonstantea);
			
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		}
	
}


